package com.example.dml.proxy_pattern.dynamic_proxy;

import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.cglib.proxy.Proxy;

import javax.servlet.Registration;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Authors：gaoyang
 * @CreateTime：2021-10-27
 * @Description：todo
 */
public class OrderServiceDynamicProxy implements InvocationHandler {

    private SimpleDateFormat format = new SimpleDateFormat("yyyy");
    private Object target;

    public Object getInstance(Object target){
        this.target = target;
        Class<?>clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(),clazz.getInterfaces(),this);
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before(args[0]);
        Object obj = method.invoke(target,args);
        after();
        return obj;
    }

    private void before(Object target){
        try {
            System.out.println("proxy before method");
            Long time = (Long) target.getClass().getMethod("getCreateTime").invoke(target);
            Integer dbRouter = Integer.valueOf(format.format(new Date(time)));
            System.out.println("静态代理类自动分配到【DB_"+dbRouter+"】数据源处理数据");
        }catch (Exception e){

        }

    }
    private void after(){
        System.out.println("proxy after method");
    }
}
